<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

const animationDuration = 6000

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '90%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData:{
    	type: Array,
    	default:()=> []
    },
    xAxisData:{
    	type: Array,
    	default: ()=> []
		},
		xRotate:{
    	default: '0'
		},
    dataName:{
    	type: String,
    	default: '数据'
    },
    yAname:{
    	type: String,
    },
    xAname:{
    	type: String,
    },
    title: {
    	type: String,
    	default: ''
    },
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  watch: {
			chartData: {
				deep: true,
				handler(val) {
					this.setOptions(this.xAxisData,val);
				}
			}
	},
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
			this.setOptions(this.xAxisData,this.chartData);
     
    },
    setOptions(xAxisData,chartData) {
    	  let that = this;
		this.chart.setOption({
			 title : {
		        text: this.title,
		        x:'center'
		    },
	        tooltip: {
	          trigger: 'axis',
	          axisPointer: { // 坐标轴指示器，坐标轴触发有效
	            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
	          }
	        },
	        grid: {
	          top: 10,
	          left: '2%',
	          right: '2%',
	          bottom: '3%',
	          containLabel: true
	        },
	        xAxis: [{
	        	name:this.xAname,
	        	nameLocation:'end',
	          type: 'category',
	          data: xAxisData,
	          axisTick: {
	            alignWithLabel: true
	          },
	          axisLabel:{
				     interval:0,//横轴信息全部显示
				     formatter: function (value, index) {
									// 10 6 这些你自定义就行
									var v = value.substring(0, 6) + '...'
									return value.length > 6 ? v : value
							},
							rotate:this.xRotate,//-30度角倾斜显示
				}
	        }],
	        yAxis: [{
	        	name:this.yAname,
		        	nameLocation:'center',
	          type: 'value',
	          axisTick: {
	            show: true
	          }
	        }],
	        series: [{
	          name: that.dataName,
	          type: 'bar',
	          stack: 'vistors',
	          barWidth: '60%',
	          data: chartData,
	          animationDuration
	        }, ]
	      })
			}
    
  },
  
}
</script>
